package middleware

import (
	"chatgpt/helper"
	"chatgpt/helper/code"
	"chatgpt/logq"
	"chatgpt/services/token"
	"net/http"

	//"chatgpt/plugin/rpcx"
	"github.com/gin-gonic/gin"
)

func MustLogin() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.Query("AuthToken")
		//uid := "123123" //uid := model.UserMgr.GetUUIDByToken(token)
		if true {
			//ctx.Set("UUID", uid)
			ctx.Set("Token", token)
			ctx.Next()
			return
		}

		helper.Echo(ctx, code.NON_LOGIN, nil)
		logq.Warn("MIDDLE.CHECK-LOGIN.PATH", ctx.FullPath())
		ctx.Abort()
	}
}

func ApiKeyCheck() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		api_key := ctx.Query("api_key")
		//uid := "123123" //uid := model.UserMgr.GetUUIDByToken(token)
		u := token.Login.GetUserGpt(api_key)
		if u != nil {
			//ctx.Set("UUID", uid)
			ctx.Next()
			return
		}

		helper.Echo(ctx, code.NON_LOGIN, nil)
		logq.Warn("MIDDLE.CHECK-APIKEY PATH", ctx.FullPath())
		ctx.Abort()
	}
}

// 跨域
func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, DeviceID")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "true")
		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}
		context.Next()
	}
}
